package model

import (
	"gogame/lib"
	"gogame/pb"
	"time"
)

type UserInfo struct {
	*ModelInfo
}

func init() {
	model := &UserInfo{
		ModelInfo: NewModelInfo("userinfo", "uid", SetExpireTime(time.Hour*6)),
	}
	model.ModelInfo.Child = model
	Manage.models.UserInfo = model
}

// DataChange 数据改变
func (self *UserInfo) DataChange(uid, act string, datas ...any) {
	switch act {
	case "Set":
		_setData := datas[1].(map[string]any)
		if lib.InMap("loginnum", _setData) {
			Event.Emit("task1", uid)
		}
		if lib.InMap("lv", _setData) {
			Event.Emit("task2", uid)
		}
	}
}

// InitUserInfo 初始化玩家数据，载入redis 创号用
func (self *UserInfo) InitUserInfo(userInfo *pb.ModelUser) {
	self.AddModelBase(userInfo.Uid)
	self.writeRedis(userInfo.Uid, userInfo)
}

// GetGud 获取玩家gud
func (self *UserInfo) GetGud(uid string) *pb.ModelUser {
	_gud := &pb.ModelUser{}
	self.Get(uid, _gud)

	return _gud
}

func (self *UserInfo) GetIncAttr() []string {
	return []string{
		"loginnum",
	}
}

// UpdateUserInfo 更新玩家数据
func (self *UserInfo) UpdateUserInfo(uid string, setData map[string]any) map[string]any {
	_incAttr := self.GetIncAttr()
	_gud := C.Struct2Map(self.GetGud(uid))
	_setData := make(map[string]any)
	for attrKey, val := range setData {
		// 累加
		if lib.InSliceString(attrKey, _incAttr) {
			if lib.InMap(attrKey, _gud) {
				switch _gud[attrKey].(type) {
				case int32:
					_setData[attrKey] = _gud[attrKey].(int32) + val.(int32)
				case int64:
					_setData[attrKey] = _gud[attrKey].(int64) + val.(int64)
				}
			} else {
				_setData[attrKey] = val
			}
		} else {
			// 覆盖
			_setData[attrKey] = val
		}
	}
	self.Set(uid, uid, _setData)

	return _setData
}

// ChkAttrNum 检测玩家属性是否足够
func (self *UserInfo) ChkAttrNum(uid string, chkData map[string]int32) (chkRes bool, chkT string) {
	_gud := C.Struct2Map(self.GetGud(uid))
	for t, n := range chkData {
		if lib.InMap(t, _gud) {
			if _gud[t].(int32) < n {
				return false, t
			}
		} else {
			return false, t
		}
	}

	return true, ""
}
